const fetch = require('../../utils/util')
Page({
  // 页面的初始数据
  data: {
    // 当前加载的分类
    category: {},
    // 此分类下的全部店铺
    shops: [],
    pageIndex: 0,
    pageSize: 10,
    hasMore: true,
    q: ''
  },
  loadMore(q) {
    if (!this.data.hasMore) return

    let {
      pageIndex,
      pageSize
    } = this.data
    pageIndex++
    let params = {
      _page: pageIndex,
      limit: pageSize
    }
    return fetch(`categories/${this.data.category.id}/shops`, params).then(res => {
      let shops = []
      shops = this.data.shops.concat(res.data)
      let hasMore = pageIndex * pageSize < parseInt(res.header["x-total-count"])
      this.setData({
        shops,
        pageIndex,
        hasMore
      })
    })
  },
  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    fetch('categories/' + options.cat).then(res => {
      this.setData({
        category: res.data
      })
      wx.setNavigationBarTitle({
        title: res.data.name,
      })
      // 加载完分类信息过后再去加载商铺信息
      this.loadMore()
    })
  },

  // 生命周期函数--监听页面初次渲染完成
  onReady: function () {
    // onReady不一定在onLoad前面执行，而setNavigationBarTitle必须在onReady执行后才能执行
    if (this.data.category.name) {
      wx.setNavigationBarTitle({
        title: this.data.category.name,
      })
    }
  },
  // 页面上拉触底事件的处理函数
  onReachBottom() {
    this.loadMore()
  },
  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: function () {
    // 重新加载数据
    this.setData({
      shops: [],
      pageIndex: 0,
      pageSize: 10
    })
    this.loadMore().then(() => wx.stopPullDownRefresh())
  },
  searchHandle(e) {
    this.data.q = e.detail.value
  },
  searchQueryHandle() {
    let params = {
      _page: 1,
      limit: 100,
      q: this.data.q
    }
    fetch(`categories/${this.data.category.id}/shops`, params).then(res => {
      let shops = res.data
      this.setData({
        shops,
        hasMore: false
      })
    })
  },
})